<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="选择地址"
        left-arrow
        @click-left="$router.back()"
      />
    </header>
    <div class="content">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @select="onChange"
        @add="onAdd"
        @edit="onEdit"
        />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, AddressList, Toast } from 'vant'
import { getAddresslist, updateOrderAddress } from '@/api/address'
import { mapState } from 'vuex'
Vue.use(NavBar)
Vue.use(AddressList)
export default {
  data () {
    return {
      chosenAddressId: 0,
      list: []
    }
  },
  computed: {
    ...mapState({
      userid: ({ user: { userid } }) => userid
    })
  },
  methods: {
    onChange (item, index) {
      updateOrderAddress({
        userid: this.userid,
        time: this.$route.params.time,
        name: item.name,
        tel: item.tel,
        address: item.address
      }).then(() => {
        Toast('更新订单地址成功')
        this.$router.back()
      })
    },
    onAdd () {
      this.$router.push('/orderaddressadd/' + this.$route.params.time)
    },
    onEdit (item, index) {
      this.$router.push({ name: 'orderaddressedit', params: { time: this.$route.params.time, addressid: item.addressid } })
    },
    formatAddress (province, city, county) {
      let str = ''
      str = province === city ? province + county : province + city + county
      return str
    }
  },
  created () {
    getAddresslist({
      userid: this.userid
    }).then(res => {
      const addresslist = res.data.data
      addresslist.forEach((item, index) => {
        if (item.isDefault) {
          this.chosenAddressId = index
        }
        item.id = index
        item.address = this.formatAddress(item.province, item.city, item.county) + item.addressDetail
      })
      this.list = addresslist
    })
  }
}
</script>
